package com.ruoyi.controller;

import com.ruoyi.domain.entity.MyChatMessage;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import com.ruoyi.service.DouBaoAIService;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Resource
    private DouBaoAIService douBaoAIService;

    // 接收用户问题并流式返回 AI 的回答
    @PostMapping("/ask")
    public SseEmitter askQuestion(@RequestBody Map<String, String> dateMap) {
        // 创建一个 SseEmitter，用于流式返回数据
        SseEmitter emitter = new SseEmitter();

        // 异步调用 AI 服务获取数据
        new Thread(() -> {
            try {
                // 调用服务获取流式响应
                douBaoAIService.getAIResponseStream(dateMap.get("question"), emitter);
                emitter.complete(); // 流式响应完成
            } catch (Exception e) {
                try {
                    System.out.println(e.toString());
                    emitter.completeWithError(e); // 如果发生错误，结束流
                } catch (Exception ex) {
                    // 处理异常
                }
            }
        }).start();

        return emitter;
    }

    // 多次连续问答
    @PostMapping("/mulAsk")
    public SseEmitter mulAskQuestion(@RequestBody List<MyChatMessage> messageList ){
        System.out.println(messageList);
        // 创建一个 SseEmitter，用于流式返回数据
        SseEmitter emitter = new SseEmitter();
        // 异步调用 AI 服务获取数据
        new Thread(() -> {
            try {
                // 调用服务获取流式响应
                douBaoAIService.getAIMulAskStream(messageList,emitter);
                emitter.complete(); // 流式响应完成
            } catch (Exception e) {
                try {
                    System.out.println(e.toString());
                    emitter.completeWithError(e); // 如果发生错误，结束流
                } catch (Exception ex) {
                    // 处理异常
                }
            }
        }).start();

        return emitter;
    }

}
